<template>
  <div class="conetr h-full flex flex-col">
    <div class="center-board">
      <div class="center-title">
        <h3>材料进场</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button
          icon="Download"
          type="success"
          plain
          @click="handleSubmit"
          :disabled="!canEdit"
          :loading="loading"
        >
          保存
        </el-button>
      </div>
    </div>
    <el-button v-if="canEdit" class="mb-[10px]" @click="handleAdd">新增材料信息</el-button>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      class="form flex flex-col flex-1 overflow-auto"
    >
      <BasePageTable
        :table-data="formData.tableData"
        :table-columns-data="tableColumnsData"
        height="100%"
        row-key="indexs"
        class="flex-1 overflow-auto"
      >
        <template #index="scoped">
          {{ scoped.index + 1 }}
        </template>
        <template #categoryId="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.categoryId'" :rules="formRules.categoryId">
            <el-cascader
              v-model="row.categoryId"
              placeholder="请选择品类"
              style="width: fit-content"
              :options="getMaterialCategoryList"
              :show-all-levels="false"
              :props="{
                value: 'id',
                label: 'name',
              }"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #brandId="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.brandId'" :rules="formRules.brandId">
            <div class="flex">
              <el-select
                v-model="row.brandId"
                placeholder="请选择意向品牌"
                clearable
                filterable
                class="mr-2.5"
                :disabled="handleRowDisabled(row)"
                @change="handleChangeBrand($event, row)"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.brandName"
                  :value="item.id"
                />
              </el-select>
            </div>
          </el-form-item>
        </template>
        <template #brandName="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.brandName'" :rules="formRules.brandName">
            <el-input
              v-model.trim="row.brandName"
              placeholder="请输入意向品牌"
              :disabled="handleRowDisabled(row)"
              maxlength="50"
              @change="row.brandId = ''"
            ></el-input>
          </el-form-item>
        </template>
        <template #installMan="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.installMan'" :rules="formRules.installMan">
            <el-input
              v-model.trim="row.installMan"
              placeholder="请输入安装工人"
              maxlength="50"
              :disabled="handleRowDisabled(row)"
            ></el-input>
          </el-form-item>
        </template>
        <template #installManMobile="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.installManMobile'"
            :rules="formRules.installManMobile"
          >
            <el-input
              v-model.trim="row.installManMobile"
              placeholder="请输入安装工人电话"
              maxlength="50"
              :disabled="handleRowDisabled(row)"
            ></el-input>
          </el-form-item>
        </template>
        <template #getFile="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.getFile'" :rules="formRules.getFile">
            <MultiImageUpload v-model="row.getFile" :limit="1" :disabled="handleRowDisabled(row)" />
          </el-form-item>
        </template>
        <template #installFile="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.installFile'"
            :rules="formRules.installFile"
          >
            <MultiImageUpload
              v-model="row.installFile"
              :limit="1"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #getTime="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.getTime'" :rules="formRules.getTime">
            <el-date-picker
              v-model="row.getTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择到货时间"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #installTime="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.installTime'"
            :rules="formRules.installTime"
          >
            <el-date-picker
              v-model="row.installTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择安装时间"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #status="{ row, name }">
          <el-tag :type="HOUSE_STATUS.FILLED.value === row.status ? 'success' : 'info'">
            {{ getLabelByValue(HOUSE_STATUS, row.status) }}
          </el-tag>
        </template>
        <template #operation="{ row, index }">
          <el-button
            link
            type="danger"
            icon="Delete"
            :disabled="handleRowDisabled(row)"
            @click="handleDelete(row, index)"
          >
            删除
          </el-button>
        </template>
      </BasePageTable>
      <el-form-item label="驳回理由" v-if="formData.remark">
        {{ formData.remark }}
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { useCategory } from "@/hooks/useCategory";
import { ElMessage } from "element-plus";
import HouseAPI, { ConsumerHouseConstructionMaterialInstallForm } from "@/api/house";
import BasePageTable from "@/components/BasePageTable/index.vue";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import { useBrand } from "@/hooks/useBand";
import { HOUSE_STATUS } from "@/enums/house/house-const";
import { getLabelByValue } from "@/utils/enums";
import { validatePhone } from "@/utils/formvalidate";
const { brandList, params } = useBrand(true);
const { getMaterialCategory, getMaterialCategoryList } = useCategory();

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData", "backTo"]);
const dialog = reactive({
  title: "",
  visible: false,
});
const formRef = ref();
const currentRow = ref({});
const tableColumnsData = ref([
  {
    prop: "index",
    label: "排序",
    width: 80,
    customSlot: "index",
  },
  {
    prop: "categoryId",
    label: "品类",
    showOverflowTooltip: true,
    customSlot: "categoryId",
    width: 140,
  },
  {
    prop: "brandId",
    label: "品牌",
    showOverflowTooltip: true,
    customSlot: "brandId",
    width: 140,
  },
  {
    prop: "brandName",
    label: "自定义品牌",
    showOverflowTooltip: true,
    customSlot: "brandName",
    width: 140,
  },
  {
    prop: "installMan",
    label: "安装工人",
    showOverflowTooltip: true,
    customSlot: "installMan",
    width: 140,
  },
  {
    prop: "installManMobile",
    label: "安装工人电话",
    showOverflowTooltip: true,
    customSlot: "installManMobile",
    width: 150,
  },
  {
    prop: "getFile",
    label: "到货照片",
    showOverflowTooltip: true,
    customSlot: "getFile",
    minWidth: 200,
  },
  {
    prop: "getTime",
    label: "到货时间",
    showOverflowTooltip: true,
    customSlot: "getTime",
    width: 200,
  },
  {
    prop: "installFile",
    label: "安装照片",
    showOverflowTooltip: true,
    customSlot: "installFile",
    minWidth: 200,
  },
  {
    prop: "installTime",
    label: "安装时间",
    showOverflowTooltip: true,
    customSlot: "installTime",
    width: 200,
  },
  {
    prop: "remark",
    label: "驳回理由",
    showOverflowTooltip: true,
    width: 200,
  },
  /*{
    prop: "files",
    label: "提交时间",
    showOverflowTooltip: true,
    customSlot: "files",
    width: 200,
  },
  {
    prop: "files",
    label: "确认时间",
    showOverflowTooltip: true,
    customSlot: "files",
    width: 200,
  },*/
  {
    prop: "operation",
    label: "操作",
    fixed: "right",
    width: 100,
    align: "center",
    customSlot: "operation", // 自定义插槽名称
  },
]);

const defaultFormData = () => {
  return { tableData: [] };
};

interface FormData {
  remark: "";
  tableData: Array<ConsumerHouseConstructionMaterialInstallForm>;
}

const formData = ref(defaultFormData() as unknown as FormData);
const formRules = reactive({
  categoryId: [{ required: true, message: "请输入品类信息", trigger: "change" }],
  getFile: [{ required: true, message: "请输入到货照片", trigger: "change" }],
  getTime: [{ required: true, message: "请输入到货时间", trigger: "change" }],
  installFile: [{ required: true, message: "请输入安装照片", trigger: "change" }],
  installTime: [{ required: true, message: "请输入安装时间", trigger: "change" }],
  // budgetAmount: [{ required: true, message: "请输入预算金额", trigger: "blur" }],
  // name: [{ required: true, message: "请输入工人姓名", trigger: "blur" }],
  // mobile: [
  //   { required: true, message: "请输入工人联系方式", trigger: "blur" },
  //   { validator: validatePhone, trigger: "blur" },
  // ],
  // constructionStartTime: [{ required: true, message: "请选择开工日期", trigger: "change" }],
  // constructionEndTime: [{ required: true, message: "请输入预计竣工日期", trigger: "change" }],
});

function backTo() {
  emit("backTo");
}

async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate || !formData.value.tableData.length) {
    ElMessage.error("请检查输入内容");
    return;
  }
  try {
    let params = formData.value.tableData.map((item) => {
      //超过两就传最后一个
      let categoryId = item.categoryId;
      if (Array.isArray(item.categoryId) && item.categoryId.length > 0) {
        categoryId = item.categoryId[item.categoryId.length - 1];
      }
      return {
        ...item,
        getFile: JSON.stringify(item.getFile),
        installFile: JSON.stringify(item.installFile),
        categoryId,
      };
    });
    if (fakeDeleteIds.value.length > 0) {
      let deleteArray: any[] = originalTableData.value.filter((item) => {
        return fakeDeleteIds.value.includes(item.id);
      });
      deleteArray.forEach((item) => {
        params.push({
          ...item,
          isDelete: true,
        });
      });
    }
    await HouseAPI.houseConstructionMaterialInstallEdit(params);
    ElMessage.success("成功");
    emit("loadData");
    emit("backTo");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
    //ElMessage.error("失败");
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}

const canEdit = ref(true);
// 保存原始数据,用于删除,后端要求这个数据要假删除传给后端，所以需要保存原始数据
const originalTableData = ref<ConsumerHouseConstructionMaterialInstallForm[]>([]);
const fakeDeleteIds = ref<number[]>([]);
/**
 * 显示弹窗
 * @param val 当前行数据
 * @param cannotEdit 是否不可编辑,完成材料进场就不可以编辑了
 */
async function showModal(val: ConsumerHouseConstructionMaterialInstallForm, cannotEdit = false) {
  fakeDeleteIds.value = [];
  dialog.visible = true;
  currentRow.value = val;
  await getMaterialCategory();
  const houseConstructionMaterialInstallVO = val.house.houseConstructionMaterialInstallVO || [];
  formData.value.tableData = houseConstructionMaterialInstallVO.map((item, index) => {
    return {
      ...item,
      indexs: index,
      getFile: JSON.parse(item.getFile || "[]"),
      installFile: JSON.parse(item.installFile || "[]"),
    };
  });
  originalTableData.value = Object.assign([], formData.value.tableData);
  canEdit.value = !cannotEdit;
}
function handleDelete(row: ConsumerHouseConstructionMaterialInstallForm, index: any) {
  if (index !== -1) {
    if (formData.value.tableData[index]?.id) {
      fakeDeleteIds.value.push(formData.value.tableData[index].id);
    }
    formData.value.tableData.splice(index, 1);
  }
  nextTick(() => {
    formData.value.tableData;
  });
}

function handleAdd() {
  let keys;
  if (formData.value.tableData.length === 0) {
    keys = 0;
  } else {
    keys = formData.value.tableData[formData.value.tableData.length - 1].indexs + 1;
  }
  formData.value.tableData.push({
    indexs: keys,
    brandId: undefined,
    brandName: "",
    buyDate: "",
    categoryId: undefined,
    companyId: undefined,
    companyName: "",
    contractFile: [],
    createBy: "",
    createTime: "",
    getFile: [],
    getTime: "",
    houseId: currentRow.value?.houseId,
    id: undefined,
    installFile: [],
    installMan: "",
    installManMobile: "",
    installTime: "",
    merchantUserId: undefined,
    paymentFile: [],
    remark: "",
    salesmanAfter: "",
    salesmanAfterMobile: "",
    status: HOUSE_STATUS.NOT_FILLED.value,
    store: "",
  } as unknown as ConsumerHouseConstructionMaterialInstallForm);
  console.log(formData.value.tableData);
}

function handleChangeBrand(id, row) {
  if (!id) return (row.brandName = "");
  const { brandName } = brandList.value.find((item) => item.id === id);
  row.brandName = brandName;
}

function handleRowDisabled(row: ConsumerHouseConstructionMaterialInstallForm) {
  return row.status === HOUSE_STATUS.APPROVED.value;
}
defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
@import "@/views/house/style/conetr.scss";
</style>
